package com.ruoyi.business.domain.jackyun;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;

/**
 * @author hup
 * @data 2020-06-01 18:06
 **/
public class JsonUtils {
    /**
     * json序列化特性配置。
     */
    private static final SerializerFeature[] SERIALIZER_FEATURES = new SerializerFeature[] {
            // boolean为null时输出false.
            SerializerFeature.WriteNullBooleanAsFalse,
            // 输出空置的字段.
            SerializerFeature.WriteMapNullValue,
            // 如果key不为String 则转换为String，比如Map的key为Integer
            SerializerFeature.WriteNonStringKeyAsString,
            // list为null时输出[]
            SerializerFeature.WriteNullListAsEmpty,
            // number为null时输出0
            SerializerFeature.WriteNullNumberAsZero,
            // String为null时输出"".
            SerializerFeature.WriteNullStringAsEmpty,
            // 使用枚举的重载方法toString输出值
            SerializerFeature.WriteEnumUsingToString,
            //关闭循环引用
            SerializerFeature.DisableCircularReferenceDetect
    };

    /**
     * json转换为对象
     *
     * @param json json
     * @param cls  转换的类
     * @return 对象
     */
    public static <T> T deJson(String json, Class<T> cls) {
        if (json == null || json == "") {
            return null;
        }
        return JSON.parseObject(json, cls);
    }


    /**
     * 对象转换为json
     *
     * @param obj 对象
     * @return json字符串
     */
    public static String toJson(Object obj) {
        if (obj == null) {
            return "";
        }

        if (obj instanceof String) {
            return obj.toString();
        }

        // 过滤掉所有注解。
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().add("metas");

        return JSON.toJSONString(obj, filter);
    }
}
